package middleware

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/pkg"
	jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
	"net/http"
	apis2 "tuowei.com/app/api/apis"
	"tuowei.com/app/api/models"
)

func CheckLogin(ctx *gin.Context) {
	value, _ := ctx.Get(jwt.JwtPayloadKey)
	bytes, _ := json.Marshal(value)
	var obj apis2.StudentClaims
	_ = json.Unmarshal(bytes, &obj)
	if obj.Student == nil {
		ctx.AbortWithStatusJSON(http.StatusOK, map[string]interface{}{
			"code": http.StatusUnauthorized,
			"msg":  "token中不含学生信息",
			"data": nil,
		})
		return
	}
	// 查一次数据库验证是否是最新的登陆
	orm, err := pkg.GetOrm(ctx)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusOK, map[string]interface{}{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	stu := models.SysStudent{}
	err = orm.Table(models.SysStudent{}.TableName()).Where("id = ?", obj.Student.Id).First(&stu).Error
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusOK, map[string]interface{}{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	if stu.Logined != "" && stu.Logined != obj.Student.Logined {
		ctx.AbortWithStatusJSON(http.StatusOK, map[string]interface{}{
			"code": http.StatusConflict,
			"msg":  "您的账号已经在别的地方登录",
			"data": nil,
		})
		return
	}
	ctx.Next()
}
